//
//  BHQRCodeReaderController.m
//  BHQRCode
//
//  Created by sun binhua on 2017/2/22.
//  Copyright © 2017年 sun binhua. All rights reserved.
//

#import "BHQRCodeReaderController.h"
#import <AVFoundation/AVFoundation.h>

/**
 *  屏幕 高 宽 边界
 */
#define SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height
#define SCREEN_WIDTH  [UIScreen mainScreen].bounds.size.width
#define SCREEN_BOUNDS  [UIScreen mainScreen].bounds

#define SCAN_Y (SCREEN_HEIGHT-220)/2
#define SCAN_X (SCREEN_WIDTH-220)/2

#define kScanRect CGRectMake(SCAN_X, SCAN_Y, 220, 220)


@interface BHQRCodeReaderController ()<AVCaptureMetadataOutputObjectsDelegate>
{
    CAShapeLayer *cropLayer;
    BOOL upOrDown;
    int num;
    NSTimer *timer;
    
}
@property (nonatomic, strong) AVCaptureDevice *device;
@property (nonatomic, strong) AVCaptureDeviceInput *input;
@property (nonatomic, strong) AVCaptureMetadataOutput *output;
@property (nonatomic, strong) AVCaptureSession *session;
@property (nonatomic, strong) AVCaptureVideoPreviewLayer *preview;

@property (nonatomic, strong) UIImageView *line;

@end

@implementation BHQRCodeReaderController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
//    [self initQRCode];
   
    [self setScanView];
    
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
     [self setCropRect:kScanRect];
     [self performSelector:@selector(initQRCode) withObject:nil afterDelay:0.3];
    
}

- (void)setScanView {
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:kScanRect];
    imageView.image = [UIImage imageNamed:@"pick_bg"];
    [self.view addSubview:imageView];
    
    _line = [[UIImageView alloc] initWithFrame:CGRectMake(SCAN_X, SCAN_Y + 10, 220, 2)];
    _line.image = [UIImage imageNamed:@"line"];
    [self.view addSubview:_line];
    num = 0;
    upOrDown = NO;
    timer = [NSTimer scheduledTimerWithTimeInterval:.02 target:self selector:@selector(showAnimation) userInfo:nil repeats:YES];
    
}

- (void)showAnimation {
    if (upOrDown == NO) {
        num ++;
        _line.frame = CGRectMake(SCAN_X, SCAN_Y+10+2*num, 220, 2);
        if (2*num == 200) {
            upOrDown = YES;
        }
    }else {
        num --;
        _line.frame = CGRectMake(SCAN_X, SCAN_Y+10+2*num, 220, 2);
        if (num == 0) {
            upOrDown = NO;
        }
    }
}

- (void)setCropRect:(CGRect)cropRect {
    cropLayer = [[CAShapeLayer alloc] init];
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathAddRect(path, nil, cropRect);
    CGPathAddRect(path, nil, self.view.bounds);
    
    [cropLayer setFillRule:kCAFillRuleEvenOdd];
    [cropLayer setPath:path];
    [cropLayer setFillColor:[UIColor blackColor].CGColor];
    [cropLayer setOpacity:0.6];
    
    [cropLayer setNeedsDisplay];
    
    [self.view.layer addSublayer:cropLayer];
}

- (void) initQRCode {
    // Device
    _device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    // Input
    NSError *error;
    _input = [AVCaptureDeviceInput deviceInputWithDevice:self.device error:&error];
    if (error) {
        NSLog(@"%@",error);
        NSAssert(error, @"摄像头不可用");
    }
    
    // Output
    _output = [[AVCaptureMetadataOutput alloc] init];
    [_output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    
    // Session
    _session = [[AVCaptureSession alloc] init];
    [_session setSessionPreset:AVCaptureSessionPresetHigh];
    
    // 连续输入和输出
    if ([_session canAddInput:self.input]) {
        [_session addInput:self.input];
    }
    if ([_session canAddOutput:self.output]) {
        [_session addOutput:self.output];
    }
    
    // 设置条码类型
    _output.metadataObjectTypes = @[AVMetadataObjectTypeQRCode];
    
    // 设置扫描区域
    CGFloat y = SCAN_Y/SCREEN_HEIGHT;
    CGFloat x = SCAN_X/SCREEN_WIDTH;
    CGFloat width = 220/SCREEN_WIDTH;
    CGFloat height = 220/SCREEN_HEIGHT;
    [_output setRectOfInterest:CGRectMake(y, x, height, width)];
    
    // y 0.15625 x 0.30633802816901406 w 0.6875 h 0.38732394366197181
    
    // 添加扫描画面
    _preview = [AVCaptureVideoPreviewLayer layerWithSession:_session];
    _preview.videoGravity = AVLayerVideoGravityResizeAspectFill;
    _preview.frame = self.view.layer.bounds;
    [self.view.layer insertSublayer:_preview atIndex:0];
    
    // 开始扫描
    [_session startRunning];

}

#pragma mark - AVCaptureMetadataOutputObjectsDelegate
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection {
    
    NSString *stringValue = @"";
    NSError *error = nil;
    
    if ([metadataObjects count] > 0) {
        // 停止扫描
        [_session stopRunning];
        
        AVMetadataMachineReadableCodeObject *metadataObject = [metadataObjects objectAtIndex:0];
        stringValue = metadataObject.stringValue;
        
        
        NSArray *arry = metadataObject.corners;
        for (id temp in arry) {
            NSLog(@"%@",temp);
        }
        
    }else{
        error = [NSError errorWithDomain:@"无扫描信息" code:-1 userInfo:nil];
    }
    
    if (_bh_readerDelegate && [_bh_readerDelegate respondsToSelector:@selector(bh_readerController:getText:withError:)]) {
        [_bh_readerDelegate bh_readerController:self getText:stringValue withError:error];
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
